<template>
  <el-card class="box-card"
           :body-style="{ paddingTop: '0px' }">
    <!-- 面包屑导航 -->
    <div slot="header"
         class="clearfix">
      <bread :navone="'权限管理'"
             :navtwo="'角色列表'" />
    </div>
    <el-button class='addsolebtn'
               @click='addroleFormVisible = true'>添加角色</el-button>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色"
               :visible.sync="addroleFormVisible"
               label-position='right'>
      <el-form :model="form"
               :rules="rules"
               ref="ruleForm">
        <el-form-item label="角色名称"
                      :label-width="formLabelWidth"
                      prop='roleName'>
          <el-input v-model="form.roleName"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述"
                      :label-width="formLabelWidth"
                      prop='roleDesc'>
          <el-input v-model="form.roleDesc"
                    autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="addroleFormVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click='addroles'>确 定</el-button>
      </div>
    </el-dialog>
    <!-- 角色表格 -->
    <el-table :data="tableData"
              style="width: 100%"
              :border='true'>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-row v-for='(item1) in props.row.children'
                  :key='item1.id'>
            <!-- 一级权限 -->
            <el-col :span='4'>
              <el-tag closable
                      @close="handleClose(item1.id,props.row.id)">
                {{item1.authName}}
              </el-tag>
            </el-col>
            <!-- 二级权限 -->
            <el-col :span='20'>
              <el-row v-for='(item2) in item1.children'
                      :key='item2.id'>
                <el-col :span='6'>
                  <el-tag closable
                          @close="handleClose(item2.id,props.row.id)"
                          type='success'>
                    {{item2.authName}}
                  </el-tag>
                </el-col>
                <!-- 三级权限 -->
                <el-col :span='18'>
                  <span v-for='(item3) in
                                     item2.children'
                        :key='item3.id'>
                    <el-tag closable
                            @close="handleClose(item3.id,props.row.id)"
                            type='warning'>
                      {{item3.authName}}
                    </el-tag>
                  </span>

                  <!-- </el-row> -->
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index">
      </el-table-column>
      <el-table-column prop="roleName"
                       label="角色名称"
                       width="180">
      </el-table-column>
      <el-table-column prop="roleDesc"
                       label="角色描述"
                       width="180">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary"
                     icon="el-icon-edit"
                     plain
                     size="mini"
                     @click='getoneroles(scope.row.id)'></el-button>
          <!-- 编辑角色对话框 -->
          <el-dialog title="编辑角色"
                     :visible.sync="editroleFormVisible"
                     label-position='right'>
            <el-form :model="form"
                     :rules="rules"
                     ref="ruleForm">
              <el-form-item label="角色名称"
                            :label-width="formLabelWidth"
                            prop='roleName'>
                <el-input v-model="form.roleName"
                          autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="角色描述"
                            :label-width="formLabelWidth"
                            prop='roleDesc'>
                <el-input v-model="form.roleDesc"
                          autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer"
                 class="dialog-footer">
              <el-button @click="editroleFormVisible = false">取 消</el-button>
              <el-button type="primary"
                         @click='editroles'>确 定</el-button>
            </div>
          </el-dialog>
          <el-button type="danger"
                     icon="el-icon-delete"
                     plain
                     size="mini"
                     @click='delrole(scope.row.id)'></el-button>
          <el-button type="success"
                     icon="el-icon-check"
                     plain
                     size="mini"
                     @click='getrights(scope)'></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 权限设置对话框 -->
          <el-dialog title="权限分配"
                     :visible.sync="rightsVisible"
                     width="50%">
            <el-tree :data="rightsdata"
                     :check-on-click-node='true'
                     ref='tree'
                     show-checkbox
                     node-key="id"
                     :default-expand-all='true'
                     :default-checked-keys="choose"
                     :props="defaultProps">
            </el-tree>
            <span slot="footer"
                  class="dialog-footer">
              <el-button @click="rightsVisible = false">取 消</el-button>
              <el-button type="primary"
                         @click="editrights">确 定</el-button>
            </span>
          </el-dialog>
  </el-card>
</template>

<script>
import bread from '../bread/bread.vue'
export default {
  components: {
    bread
  },
  created () {
    this.getroles() // 启动页面时,加载表格数据
  },
  data () {
    return {
      tableData: [], // 角色表格的数据
      addroleFormVisible: false, // 控制添加对话框的显示
      editroleFormVisible: false, // 控制编辑角色对话框的显示
      rightsVisible: false, // 控制权限分配对话框的显示
      form: {}, // 添加角色表单数据
      formLabelWidth: '100px', // 控制添加角色表单的输入框长度
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      rightsdata: [], // 所有权限树的所有数据
      defaultProps: { // 设置权限树的节点
        children: 'children', // 节点
        label: 'authName' // 节点上的数据名
      },
      choose: [], // 默认选中的权限列表里面存权限id
      rolesid: null // 打开权限分配时角色的id
    }
  },
  methods: {
    // 获取所有角色
    async getroles () {
      let res = await this.$http.get('roles')
      let { meta, data } = res.data
      if (meta.status === 200) {
        this.tableData = data
      }
    },
    // 获取所有权限列表
    async getrightslist () {
      let res = await this.$http.get('rights/tree')
      let { meta, data } = res.data
      if (meta.status === 200) {
        this.rightsdata = data
      }
    },
    // 添加角色
    addroles () {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          let res = await this.$http.post('roles', this.form)
          let { meta } = res.data
          if (meta.status === 201) {
            this.$message({
              type: 'success',
              message: meta.msg
            })
            this.addroleFormVisible = false
            this.getroles()
          } else {
            this.$message.error(meta.msg)
          }
        } else {
          this.$message.error('请完整输入表单')
        }
      })
    },
    // 删除角色
    delrole (id) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await this.$http.delete(`roles/${id}`)
        let { meta } = res.data
        if (meta.status === 200) {
          this.$message({
            type: 'success',
            message: meta.msg
          })
          this.getroles()
        } else {
          this.$message.error(meta.msg)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 获取单个角色的信息
    async getoneroles (id) {
      this.editroleFormVisible = true
      let res = await this.$http.get(`roles/${id}`)
      let { meta, data } = res.data
      if (meta.status === 200) {
        this.form = data
      }
    },
    // 编辑角色
    editroles () {
      this.$refs.ruleForm.validate(async vaild => {
        if (vaild) {
          let res = await this.$http.put(`roles/${this.form.roleId}`, this.form)
          let { meta } = res.data
          if (meta.status === 200) {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
            this.editroleFormVisible = false
            this.getroles()
          } else {
            this.$message.error('修改失败')
          }
        } else {
          this.$message.error('请输入完整表单!')
        }
      })
    },
    // 获取用户权限
    async getrights (scope) {
      this.rightsVisible = true
      this.choose = []
      let res = await this.$http.get('rights/tree')
      var { meta, data } = res.data
      if (meta.status === 200) {
        this.rightsdata = data
        let res1 = await this.$http.get(`roles/${scope.row.id}`)
        let meta1 = res1.data.meta
        let data1 = res1.data.data
        if (meta1.status === 200) {
          this.rolesid = data1.roleId
          scope.row.children.forEach((value1, index1) => {
            value1.children.forEach((value2, index2) => {
              value2.children.forEach((value3, index3) => {
                this.choose.push(value3.id)
              })
            })
          })
          this.choose = Array.from(this.choose)
        }
      }
    },
    // 设置用户权限
    async editrights () {
      let arr = this.$refs.tree.getCheckedKeys()
      let newarr = this.$refs.tree.getHalfCheckedKeys()
      let arr1 = new Set([...arr, ...newarr])
      let str = Array.from(arr1._c).join()
      let res = await this.$http.post(`roles/${this.rolesid}/rights`, { rids: str })
      let { meta } = res.data
      if (meta.status === 200) {
        this.$message({
          type: 'success',
          message: meta.msg
        })
        this.rightsVisible = false
        this.getroles()
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 删除某个权限
    async handleClose (rid, uid) {
      let res = await this.$http.delete(`roles/${uid}/rights/${rid}`)
      let { meta, data } = res.data
      if (meta.status === 200) {
        this.$message({
          type: 'success',
          message: meta.msg
        })
        // 遍历表格数据,根据id找到删除权限的角色,然后将删除权限返回的数据复制给他
        this.tableData.some((value, index) => {
          if (value.id === uid) {
            value.children = data
          }
        })
      } else {
        this.$message.error(meta.msg)
      }
    }
  }
}
</script>

<style scoped>
.el-tag {
  margin: 5px;
}
</style>
